import React, { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'

import { message, Input, Divider, Button, Image } from 'antd';
import { CheckShieldOutline, UserOutline, UnlockOutline } from 'antd-mobile-icons'

import { jumpTo } from '../../utils/jump'

import { getSession, getVerificationCode, startLogin } from '../../utils/axiosRequest/api'
import { session_cache_key, token_cache_key, userName_cache_key } from '../../utils/cache/cacheKey'
import { setCache, removeAllCache } from '../../utils/cache/'
//加解密
import { encryptMD5 } from "../../utils/crypt/index"

import styles from './index.module.css'


function Login() {
    //导航
    const navigate = useNavigate()
    //消息提示
    const [messageApi, contextHolder] = message.useMessage();
    const [userName, setUserName] = useState('')
    const [userPwd, setUserPwd] = useState('')
    const [captcha, seCaptcha] = useState("")
    //验证码
    const [img, setImg] = useState("")
    const [key, setKey] = useState("")
    //点击登录加载状态
    const [isLoadState, seLoadState] = useState(false)

    //[]空数组相当于componentDidMount
    useEffect(() => {
        //先获取session
        getSessionInfo()
        //返回的函数相当于unmountComponentAtNode
        return () => {

        }
    }, []);

    function getSessionInfo() {
        const timestamp = Date.now().toString();
        const issue = "hm";
        const version = "V100";
        const channel = "web";
        const author = "PCS";
        const permission = "10117aaa";
        //签名按照顺序channel->version->author->permission->issue全小写再md5
        const signature = timestamp.toLowerCase() + channel.toLowerCase() + version.toLowerCase() + author.toLowerCase() + permission.toLowerCase() + issue.toLowerCase()
        //构建请求参数
        const params = new Map()
        params.set('timestamp', timestamp)
        params.set('issue', issue)
        params.set('version', version)
        params.set('channel', channel)
        params.set('author', author)
        params.set('permission', permission)
        params.set('signature', encryptMD5(signature))
        getSession(params)
            .then(response => {
                const data = response.data
                if (data.code === '000') {
                    //先删除所有缓存
                    removeAllCache()
                    //保存session
                    setCache(session_cache_key, data.data.sessionId);
                    //获取验证码
                    getVerification()
                } else {
                    //处理失败
                    messageApi.open({ type: 'error', content: data.des });
                }
            })
            .catch(error => {
                messageApi.open({ type: 'error', content: error.message });
            });
    }

    function getVerification() {
        const params = new Map()
        getVerificationCode(params)
            .then(response => {
                const data = response.data
                if (data.code === '000') {
                    setImg('data:image/png;base64,' + data.data.imgBase64)
                    setKey(data.data.captchaKey)
                } else {
                    //处理失败
                    messageApi.open({ type: 'error', content: data.des });
                }
            })
            .catch(error => {
                messageApi.open({ type: 'error', content: error.message });
            });
    }

    function onChangeUserName(val) {
        let userName = val.target.value
        setUserName(userName);
    }

    function onChangeUserPwd(val) {
        let userPwd = val.target.value
        setUserPwd(userPwd);
    }

    function onCaptcha(val) {
        let captcha = val.target.value
        seCaptcha(captcha);
    }

    function clickCaptcha() {
        getVerification()
    }

    function clickLogin() {
        if (userName.length === 0) {
            messageApi.open({ type: 'error', content: '请输入账号！' });
            return
        }
        if (userPwd.length === 0) {
            messageApi.open({ type: 'error', content: '请输入密码！' });
            return
        }
        if (captcha.length === 0) {
            messageApi.open({ type: 'error', content: '请输入验证码！' });
            return
        }
        if (captcha.length !== 6) {
            messageApi.open({ type: 'error', content: '请输入6位数验证码！' });
            return
        }
        seLoadState(prevState => !prevState);
        const params = new Map()
        params.set('captchaKey', key)
        params.set('captcha', captcha)
        params.set('userName', userName)
        params.set('pwd', userPwd)
        startLogin(params)
            .then(response => {
                const data = response.data
                if (data.code === "000") {
                    //保存token
                    setCache(token_cache_key, data.data.accessToken);
                    setCache(userName_cache_key, data.data.userName);
                    //登录成功
                    jumpTo(navigate, '/main/map', true, null)
                } else {
                    messageApi.open({ type: 'error', content: data.des });
                }
                seLoadState(prevState => !prevState);
            })
            .catch(error => {
                messageApi.open({ type: 'error', content: error.message });
                seLoadState(prevState => !prevState);
            });
    }

    return (
        <div className={styles.container}>
            {contextHolder}
            <div className={styles.login_box}>
                <div className={styles.title}>
                    <Divider style={{ paddingLeft: '50px', paddingRight: '50px', borderColor: '#0085d0', }}>
                        <span className={styles.title_font}>推送管理平台</span>
                    </Divider >
                </div>
                <div className={styles.user_name_box}>
                    <Input onChange={onChangeUserName} value={userName} className={styles.user_name} maxLength='10'
                        placeholder='请输入账号...' allowClear={true} prefix={<UserOutline />} size="large" />
                </div>
                <div className={styles.user_pwd_box}>
                    <Input value={userPwd} onChange={onChangeUserPwd} className={styles.user_pwd} maxLength='20'
                        type={'password'} placeholder='请输入密码...' allowClear={true} prefix={<UnlockOutline />} size="large" />
                </div>
                <div className={styles.verification_box}>
                    <div className={styles.verification_con}>
                        <Input value={captcha} onChange={onCaptcha} className={styles.verification} maxLength='6'
                            type={'number'} placeholder='验证码' allowClear={true} prefix={<CheckShieldOutline />} size="large" />
                        <div className={styles.verification_img}>
                            <Image onClick={clickCaptcha} height={"40px"} width={"150px"} src={img} preview={false} placeholder={true}></Image>
                        </div>
                    </div>
                </div>
                <div className={styles.login_button_box}>
                    <Button loading={isLoadState} onClick={clickLogin} className={styles.login_button} type="primary" size={'large'}>点击登录</Button>
                </div>
            </div>
        </div>
    )
}

export default Login;
